<template>
    <div class="common-layout">
        <el-container>
            <el-aside>
                <el-scrollbar>
                    <el-input v-model="deptName" placeholder="请输入部门名称" clearable>
                        <template #prefix>
                            <el-icon>
                                <ep-Search />
                            </el-icon>
                        </template>
                    </el-input>
                    <el-tree
                        ref="treeRef"
                        :data="treeData"
                        :props="defaultProps"
                        :node-key="treeData.id"
                        :filter-node-method="filterNode"
                        @node-click="handleNodeClick"
                        highlight-current
                        accordion
                    />
                </el-scrollbar>
            </el-aside>
            <el-container>
                <el-header>
                    <el-form ref="formRef" :model="userQureyform" label-width="auto" inline>
                        <el-form-item label="用户名称" prop="name">
                            <el-input
                                v-model="userQureyform.name"
                                placeholder="请输入用户名称"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item label="手机号" prop="phoneNumber">
                            <el-input
                                v-model="userQureyform.phoneNumber"
                                placeholder="请输入手机号"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input
                                v-model="userQureyform.email"
                                placeholder="请输入邮箱"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item label="账号状态" prop="status">
                            <el-select
                                v-model="userQureyform.status"
                                placeholder="请选择状态"
                                style="width: 170px"
                                clearable
                            >
                                <el-option
                                    v-for="item in statusOptions.options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="创建时间" prop="dateRange">
                            <el-date-picker
                                v-model="userQureyform.dateRange"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm(formRef)">
                                <el-icon>
                                    <ep-Search />
                                </el-icon>
                                <span>搜索</span>
                            </el-button>
                            <el-button @click="resetForm(formRef)">
                                <el-icon>
                                    <ep-Refresh />
                                </el-icon>
                                <span>重置</span>
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-header>
                <el-main>
                    <div>
                        <el-button v-if="hasPermission('system:user:add')" plain @click="handleAdd">
                            <el-icon>
                                <ep-Plus />
                            </el-icon>
                            <span>新增</span>
                        </el-button>
                        <!-- <el-button type="success">
                            <el-icon>
                                <ep-Upload />
                            </el-icon>
                            <span>导出</span>
                        </el-button> -->
                    </div>
                    <el-table :data="tableData" stripe>
                        <el-table-column type="selection" align="center" />
                        <!-- <el-table-column label="用户ID" prop="id" align="center"  /> -->
                        <el-table-column label="用户名称" prop="name" align="center" width="150" />
                        <el-table-column label="部门" prop="deptName" align="center" width="150" />
                        <el-table-column
                            label="手机号码"
                            prop="phoneNumber"
                            align="center"
                            width="120"
                        />
                        <el-table-column label="邮箱" prop="email" align="center" width="180" />
                        <el-table-column label="账号状态" align="center" width="100">
                            <template #default="scope">
                                <template v-if="showSwitchButton">
                                    <el-switch
                                        v-model="scope.row.isUsed"
                                        size="large"
                                        inline-prompt
                                        active-text="启用"
                                        inactive-text="停用"
                                        :disabled="!hasPermission('system:user:edit')"
                                        @change="handleStatusChange(scope.row)"
                                    />
                                </template>
                                <template v-else>
                                    <el-tag v-if="scope.row.status" type="success">
                                        {{ scope.row.statusDesc }}
                                    </el-tag>
                                    <el-tag v-else type="danger">
                                        {{ scope.row.statusDesc }}
                                    </el-tag>
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="创建人"
                            prop="createBy"
                            align="center"
                            width="150"
                        />
                        <el-table-column
                            label="创建时间"
                            prop="createTime"
                            align="center"
                            width="200"
                        />
                        <el-table-column
                            label="备注"
                            prop="remark"
                            align="center"
                            show-overflow-tooltip
                        />
                        <el-table-column label="操作" align="center" fixed="right" min-width="180">
                            <template #default="scope">
                                <el-tooltip
                                    v-if="hasPermission('system:user:detail')"
                                    effect="dark"
                                    content="查看详情"
                                    placement="top"
                                >
                                    <el-button
                                        size="small"
                                        type="info"
                                        @click="handleDetail(scope.$index, scope.row)"
                                        link
                                    >
                                        <el-icon><ep-Warning /></el-icon>
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip
                                    v-if="hasPermission('system:user:edit')"
                                    effect="dark"
                                    content="编辑用户"
                                    placement="top"
                                >
                                    <el-button
                                        size="small"
                                        type="warning"
                                        disabled="hasPermission('system:user:edit')"
                                        @click="handleEdit(scope.$index, scope.row)"
                                        link
                                    >
                                        <el-icon><ep-Edit /></el-icon>
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip
                                    v-if="hasPermission('system:user:remove')"
                                    effect="dark"
                                    content="删除用户"
                                    placement="top"
                                >
                                    <el-button
                                        size="small"
                                        type="danger"
                                        @click="handleDelete(scope.$index, scope.row)"
                                        link
                                    >
                                        <el-icon><ep-Delete /></el-icon>
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip
                                    v-if="showMoreAction"
                                    effect="dark"
                                    content="更多操作"
                                    placement="top"
                                >
                                    <el-dropdown trigger="click" v-if="showMoreAction">
                                        <el-button
                                            size="small"
                                            type="info"
                                            class="user-more-action"
                                            link
                                        >
                                            <el-icon><ep-DArrowRight /></el-icon>
                                        </el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item
                                                    v-if="hasPermResetPwd"
                                                    @click="handleResetPwd(scope.$index, scope.row)"
                                                >
                                                    <el-icon><ep-Key /></el-icon>
                                                    <span>重置密码</span>
                                                </el-dropdown-item>
                                                <el-dropdown-item
                                                    v-if="hasPermSetUserRole"
                                                    @click="handleSetRole(scope.$index, scope.row)"
                                                >
                                                    <el-icon><ep-CircleCheck /></el-icon>
                                                    <span>分配角色</span>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        v-show="total > userQureyform.pageSize"
                        :total="total"
                        :page-sizes="[20, 100, 200, 300, 400]"
                        v-model:current-page="userQureyform.pageNum"
                        v-model:page-size="userQureyform.pageSize"
                        layout="total,sizes,prev,pager,next,jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        background
                    />
                </el-main>
            </el-container>
        </el-container>
        <div class="dialog-container">
            <add-user />
            <edit-user />
            <user-detail />
            <user-setRole />
        </div>
    </div>
</template>
<script setup name="User">
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import { ref, reactive, computed, onActivated, nextTick, watch, useTemplateRef, provide } from 'vue'
import { handleChildreNode, handleAttributes, hasPermission } from '@/utils/common'
import { getDeptTree } from '@/api/system/dept'
import { getUserList, editUserStatus, deleteUser, resetUserPwd } from '@/api/system/user'
import userDetail from './userDetail.vue'
import addUser from './addUser.vue'
import editUser from './editUser.vue'
import userSetRole from './userSetRole.vue'
import useStore from '@/stores'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const { settings } = useStore()

const showSwitchButton = computed(() => settings.showSwitchButton)
const showMoreAction = computed(() => hasPermResetPwd.value || hasPermSetUserRole.value)

const deptName = ref('')
const treeData = ref([])
const tableData = ref([])
const total = ref(0)

const hasPermResetPwd = ref(false)
const hasPermSetUserRole = ref(false)

const statusOptions = reactive({
    options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
    ]
})

const addUserVisible = ref(false)
const editUserVisible = ref(false)
const selectedRow = ref({})
const selectedRowId = ref(undefined)
const userDetailVisible = ref(false)
const userSetRoleVisible = ref(false)

const treeRef = useTemplateRef('treeRef')
const formRef = useTemplateRef('formRef')

provide('userDetail', {
    userDetailVisible,
    selectedRow
})
provide('editUser', {
    editUserVisible,
    selectedRow
})
provide('addUser', {
    addUserVisible
})
provide('userSetRole', {
    userSetRoleVisible,
    selectedRowId
})

const defaultProps = {
    children: 'children',
    label: 'label'
}
const userQureyform = reactive({
    deptId: undefined,
    name: undefined,
    phoneNumber: undefined,
    email: undefined,
    status: undefined,
    startDate: undefined,
    endDate: undefined,
    dateRange: undefined,
    pageNum: 1,
    pageSize: 20
})
const editUserStatusform = reactive({
    id: undefined,
    status: undefined
})
/**
 * 根据输入框的值过滤树节点
 */
watch(deptName, (val) => {
    treeRef.value.filter(val)
})
/**
 * 获取部门树
 */
function selectDeptTree() {
    getDeptTree().then((response) => {
        if (response) {
            handleChildreNode(response.data)
            handleAttributes(response.data)
            treeData.value = response.data
        }
    })
}
/**
 * 过滤树节点,返回false的会被隐藏
 * @param value
 * @param data
 */
function filterNode(value, data) {
    if (!value) return true
    return data.label.includes(value)
}
/**
 * 当tree节点被点击的时候触发
 * @param data  被点击节点的数据对象
 * @param node  TreeNode 的 node 属性
 * @param component  被点击节点的组件实例
 * @param event 原生 DOM 事件对象
 */
function handleNodeClick(data, node, component, event) {
    userQureyform.deptId = data.id
    submitForm()
}
/**
 * 提交表单
 */
function submitForm() {
    _getUserList()
}

/**
 *  修改用户状态
 * @param row    行数据
 */
function handleStatusChange(row) {
    editUserStatusform.id = row.id
    editUserStatusform.status = row.isUsed ? 1 : 0
    editUserStatus(editUserStatusform).then(() => {
        // 重置表单
        Object.keys(editUserStatusform).forEach((key) => {
            editUserStatusform[key] = undefined
        })
        // 刷新表格
        const { query, path } = route
        router.replace({ path: '/redirect' + path, query: query })
    })
}
function _getUserList() {
    if (userQureyform.dateRange && userQureyform.dateRange.length !== 0) {
        if (userQureyform.dateRange.length !== 2) {
            ElMessage.error('请选择完整的时间段!')
            return
        }
        const [startDate, endDate] = userQureyform.dateRange
        userQureyform.startDate = startDate
        userQureyform.endDate = endDate
    }
    // 删除属性不用传给后端
    delete userQureyform.dateRange
    getUserList(userQureyform).then((response) => {
        if (response && response.data) {
            response.data.forEach((item) => (item.isUsed = item.status === 1))
            tableData.value = response.data
            total.value = response.total
            updateStatusOptions(response.data)
        }
    })
}
/**
 * 更新状态选项
 * @param { array } data 用户
 */
function updateStatusOptions(data) {
    // 使用 Map 来存储唯一的 status 和对应的 statusDesc
    const statusMap = new Map(data.map((item) => [item.status, item.statusDesc]))

    // 将 Map 转换为 { label, value } 格式的数组
    const options = Array.from(statusMap.entries(), ([value, label]) => ({ label, value }))

    // 更新 statusOptions.options
    statusOptions.options = options
}
/**
 * 每页显示条数改变
 * @param number 每页显示条数
 */
function handleSizeChange(number) {
    userQureyform.pageSize = number
    _getUserList()
}
/**
 *  当前页码改变
 * @param number 当前页码
 */
function handleCurrentChange(number) {
    userQureyform.pageNum = number
    _getUserList()
}
/**
 * 重置表单
 * @param formEl 表单的ref
 */
function resetForm(formEl) {
    if (!formEl) return
    formEl.resetFields()
    userQureyform.deptId = undefined
    userQureyform.startDate = undefined
    userQureyform.endDate = undefined
    userQureyform.pageNum = 1
    userQureyform.pageSize = 20
    submitForm()
}
/**
 *  重置用户密码
 * @param index   索引
 * @param row     行数据
 */
function handleResetPwd(index, row) {
    ElMessageBox.confirm(`请输入${row.name}的新密码`, '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showInput: true,
        inputPlaceholder: '请输入密码',
        inputPattern: /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{6,20}$/,
        inputErrorMessage: '密码长度在6-20位之间,且只能包含字母、数字、特殊字符'
    })
        .then(({ value }) => {
            const resetPwdForm = { id: row.id, password: value }
            resetUserPwd(resetPwdForm).then(() => {
                const { query, path } = route
                router.replace({ path: '/redirect' + path, query: query })
            })
        })
        .catch(() => {})
}
/**
 *  为用户设置角色
 * @param index   索引
 * @param row     行数据
 */
function handleSetRole(index, row) {
    selectedRowId.value = row.id
    userSetRoleVisible.value = true
}
/**
 *  用户详情
 * @param index   索引
 * @param row     行数据
 */
function handleDetail(index, row) {
    selectedRow.value = row
    userDetailVisible.value = true
}
/**
 *  新增用户
 * @param index   索引
 * @param row     行数据
 */
function handleAdd() {
    addUserVisible.value = true
}
/**
 * 编辑用户
 *  @param index   索引
 *  @param row     行数据
 */
function handleEdit(index, row) {
    selectedRow.value = row
    editUserVisible.value = true
}
/**
 *  删除用户
 * @param index   索引
 * @param row     行数据
 */
function handleDelete(index, row) {
    ElMessageBox.confirm('确定执行删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    })
        .then(() => {
            deleteUser(row.id).then(() => {
                // 刷新表格
                const { query, path } = route
                router.replace({ path: '/redirect' + path, query: query })
            })
        })
        .catch(() => {})
}
// 在组件被激活时执行的操作
onActivated(() => {
    nextTick(() => {
        hasPermResetPwd.value = hasPermission('system:user:resetPwd')
        hasPermSetUserRole.value = hasPermission('system:user:setUserRole')
        selectDeptTree()
        submitForm()
    })
})
</script>
<style lang="scss" scoped>
.common-layout {
    box-sizing: border-box;
    height: 100vh;
    padding: 20px;
    background-color: #f5f5f5;

    & .el-container {
        & > * {
            // @include border($border-color: red);
            background-color: #fff;
        }

        & .el-header {
            padding-top: 15px;
            height: 23%;
        }

        & .el-container {
            background-color: #f5f5f5;
        }

        & .el-aside {
            width: 200px;
            margin-right: 15px;

            & .el-tree {
                height: calc(100vh - 160px);
            }
        }

        & .el-main {
            margin-top: 15px;

            & .user-more-action {
                margin-top: 5px;
                margin-left: 5px;
            }
        }
    }
}

/* 媒体查询：屏幕宽度小于1024px */
@media (max-width: 1023px) {
}
</style>
